﻿/*! @file extdevicedlg.cpp
  * @brief Implements class ExtDeviceDlg
  * @author AK
  * @date 08.08.2012
  */

#include "extdevicedlg.h"
#include "extdevice.h"
#include <QtGui>

/** @brief Implementation of ExtDeviceDlg
 * GUI created programmatically here - just for fun
 * @callgraph
 * @callergraph
 *
 * @param deviceList: QList<QString>
 */
ExtDeviceDlg::ExtDeviceDlg(QList<QString> deviceList, QWidget *parent)
    : QDialog(parent)
{
#ifdef Q_OS_WIN
    QTextCodec::setCodecForTr(QTextCodec::codecForName("Latin1" /*"Windows-1252"*/));
#else
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
#endif
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

    // get last expoDir from settings file
    QString templatePath = QApplication::applicationDirPath () + "/templates";
    if(!QFile(templatePath + "/PPSettings.ini").exists()) {
        expoDir = QDir::homePath();
        qDebug() << "ini file does not exist";
    }
    else {
        QSettings settings (templatePath + "/PPSettings.ini", QSettings::IniFormat);
        settings.beginGroup("LastExpoDir");
        expoDir = settings.value("lastExpoDir", QDir::homePath()).toString();
    }

    // setup all widgets
    deviceLabel = new QLabel(tr("Gerät"));
    deviceStatusLabel = new QLabel(tr("\tStatus:"));
    deviceStatus = new QLabel();
    deviceStatus->setPixmap(QPixmap(QPixmap(":/icons/res/sm-failed.png")));
    deviceStatus->setToolTip(tr("Status"));
    deviceRootedLabel = new QLabel(tr(" rooted?"));
    deviceRooted = new QLabel();
    deviceRooted->setPixmap(QPixmap(QPixmap(":/icons/res/sm-failed.png")));
    deviceRooted->setToolTip(tr("gerooted?"));
    statusSpacer = new QSpacerItem(20, 10, QSizePolicy::Expanding, QSizePolicy::Fixed);
    deviceComboBox = new QComboBox();
    deviceComboBox->addItems(deviceList);
    getProviderDbsButton = new QPushButton(tr("Exportliste bearbeiten"));
    providerSpacer = new QSpacerItem(20, 10, QSizePolicy::Expanding, QSizePolicy::Fixed);
    deviceModelLabel = new QLabel();
    reloadDevicesButton = new QPushButton(QIcon(":/icons/res/reload_32.png"), NULL);
    expoFolderLabel = new QLabel(tr("Export Verzeichnis"));
    expoFolderEdit = new QLineEdit(QDir::toNativeSeparators(expoDir));
    openExpoDirButton = new QPushButton(QIcon(":/icons/res/openfolder_32.png"), NULL);
    logLabel = new QLabel(tr("Log"));
    logTextEdit = new QTextEdit();
    buttonSpacer = new QSpacerItem(20, 10, QSizePolicy::Expanding,
                                   QSizePolicy::Fixed);
    getPropsButton = new QPushButton(tr("Details"));
    getLogButton = new QPushButton(tr("Logs"));
    okButton = new QPushButton(tr("&Export"));
    okButton->setDefault(true);
    closeButton = new QPushButton(tr("Fertig"));

    reloadDevicesButton->setFixedSize(40, 20);
    //reloadDevicesButton->setEnabled(false);
    openExpoDirButton->setFixedSize(40, 20);

    connect(deviceComboBox, SIGNAL(currentIndexChanged(QString)),
            this, SLOT(setDevice(QString)));
    connect(getProviderDbsButton, SIGNAL(clicked()),
            this, SLOT(on_getProviderDbsButtonClicked()));
    connect(openExpoDirButton, SIGNAL(clicked()),
            this, SLOT(on_openExpoDirButtonClicked()));
    connect(reloadDevicesButton, SIGNAL(clicked()),
            this, SLOT(on_reloadDeviceButtonClicked()));
    connect(getLogButton, SIGNAL(clicked()),
            this, SLOT(on_getLogButtonClicked()));
    connect(getPropsButton, SIGNAL(clicked()),
            this, SLOT(on_getPropsButtonClicked()));
    connect(okButton, SIGNAL(clicked()),
            this, SLOT(on_okButtonClicked()));
    connect(closeButton, SIGNAL(clicked()),
            this, SLOT(close()));
    connect(closeButton, SIGNAL(clicked()),
            this, SLOT(on_closeButtonClicked()));

    QHBoxLayout *statusLayout = new QHBoxLayout;
    statusLayout->addWidget(deviceLabel);
    statusLayout->addWidget(deviceStatusLabel);
    statusLayout->addWidget(deviceStatus);
    statusLayout->addWidget(deviceRootedLabel);
    statusLayout->addWidget(deviceRooted);
    statusLayout->addItem(statusSpacer);
    QHBoxLayout *comboLayout = new QHBoxLayout;
    comboLayout->addWidget(deviceComboBox);
    comboLayout->addWidget(getProviderDbsButton);
    comboLayout->addItem(providerSpacer);
    comboLayout->addWidget(deviceModelLabel);
    comboLayout->addWidget(reloadDevicesButton);

    QHBoxLayout *expoLayout = new QHBoxLayout;
    expoLayout->addWidget(expoFolderEdit);
    expoLayout->addWidget(openExpoDirButton);

    QVBoxLayout *topLayout = new QVBoxLayout;
    topLayout->addLayout(statusLayout);
    topLayout->addLayout(comboLayout);
    topLayout->addWidget(expoFolderLabel);
    topLayout->addLayout(expoLayout);
    topLayout->addWidget(logLabel);
    topLayout->addWidget(logTextEdit);

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(getPropsButton);
    buttonLayout->addWidget(getLogButton);
    buttonLayout->addItem(buttonSpacer);
    buttonLayout->addWidget(okButton);
    buttonLayout->addWidget(closeButton);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addLayout(topLayout);
    mainLayout->addLayout(buttonLayout);
    setLayout(mainLayout);

    setWindowTitle(tr("angeschlossene Geräte"));
    setMinimumHeight(500);
    setMinimumWidth(600);
}

/**
 * @brief disables closeButton
 *
 * @fn ExtDeviceDlg::disableCloseButton
 */
void ExtDeviceDlg::disableCloseButton()
{
    closeButton->setEnabled(false);
}

/**
 * @brief enables closeButton
 *
 * @fn ExtDeviceDlg::enableCloseButton
 */
void ExtDeviceDlg::enableCloseButton()
{
    closeButton->setEnabled(true);
}

/**
 * @brief ExtDeviceDlg::getActiveDevice
 * @return activeDevice
 */
QString ExtDeviceDlg::getActiveDevice()
{
    return deviceComboBox->currentText();
}

/**
 * @brief closeButton clicked -> expoDone
 *
 * @fn ExtDeviceDlg::on_closeButtonClicked
 */
void ExtDeviceDlg::on_closeButtonClicked()
{
    Q_EMIT expoDone();
}

/**
 * @brief emits directoryChanged, sets expoDir
 *
 * @fn ExtDeviceDlg::on_expoFolderEditChanged
 */
void ExtDeviceDlg::on_expoFolderEditChanged()
{
    okButton->setEnabled(true);
    expoDir = expoFolderEdit->text();
    Q_EMIT directoryChanged(expoFolderEdit->text());
}

void ExtDeviceDlg::on_getLogButtonClicked()
{
    Q_EMIT logRequest(deviceComboBox->currentText());
}

/**
 * @brief emits a propertiesRequest
 *
 * @fn ExtDeviceDlg::on_getPropsButtonClicked
 */
void ExtDeviceDlg::on_getPropsButtonClicked()
{
    Q_EMIT propertiesRequest(deviceComboBox->currentText());
}

/**
 * @brief ExtDeviceDlg::on_getProviderDbsButtonClicked
 * this emits providerRequest to ExtDevice, provider Dialog gets opened
 * from there.
 */
void ExtDeviceDlg::on_getProviderDbsButtonClicked()
{
    qDebug() << "ExtDeviceDlg|in on_getProviderDbsButtonClicked()";

    Q_EMIT providerRequest(deviceComboBox->currentText());
}

/** @brief should emit selected db files
 * @callgraph
 * @callergraph
 *
 *@returns QString selected ComboBox Text. aka Device
 *@todo return real file handles
 */
void ExtDeviceDlg::on_okButtonClicked()
{
    QString expoDevice = deviceComboBox->currentText();
    expoDir = expoFolderEdit->text();

    Q_EMIT deviceChanged(selectedDevice);
    Q_EMIT gotDevice(deviceComboBox->currentText());
    Q_EMIT doExport(expoDevice, expoDir);

    okButton->setEnabled(false);
}

/**
 * @brief open FileDialog and sets expoDir
 *
 * @fn ExtDeviceDlg::on_openExpoDirButtonClicked
 */
void ExtDeviceDlg::on_openExpoDirButtonClicked()
{
    QString dir = QFileDialog::getExistingDirectory (this, tr("Verzeichnis öffnen"),
                               expoFolderEdit->text(),
                               QFileDialog::ShowDirsOnly);
    if (dir.isEmpty ()) {
        dir = QDir::homePath();
        return;
    }

    expoDir = dir;
    expoFolderEdit->setText(QString(QDir::toNativeSeparators(expoDir)));
    okButton->setEnabled(true);
    Q_EMIT directoryChanged(expoDir);
}

/**
 * @brief ExtDeviceDlg::on_reloadDeviceButtonClicked
 * @note for now its to test uid stuff on device
 */
void ExtDeviceDlg::on_reloadDeviceButtonClicked()
{
    QString expoDevice = deviceComboBox->currentText();
    Q_EMIT reloadDevices(expoDevice);
}

/**
 * @brief sets tooltip with device properties
 *
 * @fn ExtDeviceDlg::setComboToolTip
 * @param text
 */
void ExtDeviceDlg::setComboToolTip(QString status, QString model,
                                   QString rooted, QString uid, QString text)
{
//    qDebug() << status << model << rooted << uid << text;
    deviceLabel->setText(model);
    deviceLabel->setToolTip(text);
    deviceComboBox->setToolTip(text);
    deviceStatusLabel->setToolTip(status);
    deviceStatus->setToolTip(status);
    deviceRootedLabel->setToolTip(uid);
    deviceRooted->setToolTip(uid);

    if(status == "device")
        deviceStatus->setPixmap(QPixmap(":/icons/res/sm-success.png"));
    else if(status == "offline")
        deviceStatus->setPixmap(QPixmap(":/icons/res/sm-alertO.png"));
    else
        deviceStatus->setPixmap(QPixmap(":/icons/res/sm-failed.png"));

    if(rooted == "true") {
        deviceRooted->setPixmap(QPixmap(":/icons/res/sm-success.png"));
        deviceRootedLabel->setText(tr("rooted"));
    }
    else {
        deviceRooted->setPixmap(QPixmap(":/icons/res/sm-failed.png"));
        deviceRootedLabel->setText(tr("nicht gerooted"));
        QMessageBox msgBox;
        msgBox.setText(tr("Export von nicht gerooteten Devices\nnoch nicht möglich!"));
        msgBox.exec();
    }

}

/**
 * @brief sets active device and emits deviceChanged
 *
 * @fn ExtDeviceDlg::setDevice
 * @param dev
 */
void ExtDeviceDlg::setDevice(QString dev)
{
    selectedDevice = dev;
    okButton->setEnabled(true);

    Q_EMIT deviceChanged(selectedDevice);
}

/**
 * @brief logs text to textView
 *
 * @fn ExtDeviceDlg::setLogTextViewText
 * @param output
 * @param color
 */
void ExtDeviceDlg::setLogTextViewText(QString output, QColor color)
{
    logTextEdit->setTextColor(color);
    logTextEdit->append(output);
}

